import numpy as np
import cv2
import matplotlib.pyplot as plt
import math

def imadjust(img, a, b, c, d, gamma=1):
	# 线性灰度级变换
	img[np.where(img > b)] = d
	img[np.where(img < a)] = c
	img[np.where((img <= b) | (img >= a))] = (((img[np.where((img <= b) | (img >= a))] - a) / (b - a)) ** gamma) * (d - c) + c


def imgLogTrans(img, c):
	# 输入图像为[0,1], 输出也要为[0,1], 因此需要对Img乘以10
	# 底数越大，对低灰度部分的强调就越强，对高灰度部分的压缩也就越强。
	# 相反的，如果想强调高灰度部分，则用反对数函数就可以了。
	img = c * np.log10(10 * img + 1e-10)
	return img

def inversionTrans(img):
	# 倒置变换
	return 255 - img

def binaryTrans(img, level):
	# 二值变换
	img[img <= level] = 0
	img[img >level ] = 1




def main():
	img = cv2.imread("../images/Lenna.png", 0)

	# 图像灰度反转
	img_inversion = inversionTrans(img)

	img = img / 255.0
	img_deal = img.copy()

	#img[np.where((img <= 0.6) | (img >= 0.3))] = 0
	# img[np.where((img >= 0.8))] = 0

	# 线性扩展
	imadjust(img_deal, 0.3, 0.6, 0.1, 0.9)

	# 对数扩展
	img_log = imgLogTrans(img, 2)


	# 二值化
	img_binary = img.copy()
	binaryTrans(img_binary, 0.4)

	print(img.dtype)
	plt.subplot(521),plt.imshow(img, cmap = 'gray')
	plt.title('Input Image'), plt.xticks([]), plt.yticks([])
	# plt.hist(x,bins)
	# bins: 分组数量
	plt.subplot(522),plt.hist(img.ravel(),256,[0,1]),plt.xticks([]), plt.yticks([])

	plt.subplot(523),plt.imshow(img_deal, cmap = 'gray')
	plt.title('Linear'), plt.xticks([]), plt.yticks([])
	plt.subplot(524),plt.hist(img_deal.ravel(),256,[0,1]),plt.xticks([]), plt.yticks([])

	plt.subplot(525),plt.imshow(img_log, cmap = 'gray')
	plt.title('log'), plt.xticks([]), plt.yticks([])
	plt.subplot(526),plt.hist(img_log.ravel(),256,[0,1]),plt.xticks([]), plt.yticks([])

	plt.subplot(527),plt.imshow(img_inversion, cmap = 'gray')
	plt.title('reverse'), plt.xticks([]), plt.yticks([])
	plt.subplot(528),plt.hist(img_inversion.ravel(),256,[0,256]),plt.xticks([]), plt.yticks([])

	plt.subplot(529),plt.imshow(img_binary, cmap = 'gray')
	plt.title('binary'), plt.xticks([]), plt.yticks([]),plt.xticks([]), plt.yticks([])
	


	plt.show()

def test(arr):
	arr = np.log10(arr)



if __name__ == '__main__':
	 main()
	 # arr = np.array([1,2,3])
	 # test(arr)
	 # print(arr)